package com.example.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.annotations.Param;
import com.example.annotations.PostMapping;
import com.example.annotations.RestController;
import com.example.annotations.UploadFile;
import com.example.app.AppUtils;
import com.example.app.model.AppModel;
import com.example.db.model.IPage;
import com.example.model.UploadBody;
import com.example.model.UploadModel;
import com.example.utils.ClazzScanUtils;
import com.example.utils.Results;

import java.io.File;
import java.util.List;

/**
 * @Classname AppJarController
 * @Description TODO
 * @Date 2022/8/3 23:05
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@RestController("/app")
public class AppJarController {



    @PostMapping("/page")
    public JSONObject appPageController(@Param(value = "pageNum",desc = "页码",defalultValue = "1")Integer pageNum,
                                        @Param(value = "pageSize",desc = "条数",defalultValue = "10")Integer pageSize,
                                        @Param(value = "searchParams",required = false)JSONObject object){

        if(object!=null){
            Object name=object.get("name");
            if(name != null){
                IPage<AppModel> iPage=AppUtils.getAppModel(pageNum,pageSize,String.valueOf(name));
                return Results.successLayuiTable(iPage);
            }
        }
        IPage<AppModel> iPage=AppUtils.getAppModel(pageNum,pageSize,null);
        return Results.successLayuiTable(iPage);
    }

    @PostMapping(value = "/reload",desc = "重新加载应用")
    public JSONObject reloadAppController(@Param("appId")String appId){
        AppModel appModel=AppUtils.getAppByAppId(appId);
        if(appModel == null){
            return Results.error("app不存在");
        }
        AppUtils.loadAppMpdel(appModel);
        return Results.success("重新加载成功");
    }


    @UploadFile(value = "/uploadJar",isOnly = true,size = 100000000)
    public JSONObject uploadFile(UploadBody uploadBody){
        if(uploadBody == null || uploadBody.getUploadModels()==null){
            return Results.error("上传的文件为空");
        }
        List<UploadModel> uploadModels = uploadBody.getUploadModels();
        for (int i = 0; i < uploadModels.size() ; i++) {
            UploadModel uploadModel=uploadModels.get(i);
            File file=new File(uploadModel.getPath());
            if(!uploadModel.getFileName().contains(".jar")){
                file.delete();
            }else {
                //ClazzScanUtils.onload(uploadModel.getPath(),file.getName());
            }
        }
        return Results.success("上传成功");
    }
}
